<template>
    <div class="menu">
        <template v-for="menu in menus" :key="menu.id">
            <!-- 第一步 根据不同的条件渲染出不同的内容-->
            <MenuItem :level="menu.level" v-if="!menu.children">{{ menu.title }}</MenuItem>
            <ReSubMenu :level="menu.level" v-else :data="menu"></ReSubMenu>
        </template>
    </div>
</template> 
    
<script setup lang='ts'>
import { ref } from 'vue';
import MenuItem from './MenuItem.vue';
import ReSubMenu from './ReSubMenu.vue';
import { cloneDeep } from 'lodash-es';
const menuData =
    [
        {
            title: '菜单1',
            id: 1,
            children: [
                {
                    title: '菜单1-1',
                    id: 1 - 1,
                    children: [
                        { title: '菜单1-1-1', id: 1 - 1 - 1, },
                        { title: '菜单1-1-2', id: 1 - 1 - 2 },
                        {
                            title: '菜单1-1-3', id: 1 - 1 - 3, children: [
                                { title: '菜单1-1-3-1', id: 1 - 1 - 3 - 1 }
                            ]
                        }
                    ]
                },
                { title: '菜单1-2' },
                { title: '菜单1-3' }
            ]
        },
        { title: '菜单2', id: 2 },
        {
            title: '菜单3', id: 3,
            children: [
                { title: '菜单3-1', id: 3 - 1, },
                { title: '菜单3-2', id: 3 - 2, }
            ]
        }
    ]
function mapLevel(menuData, level = 1) {
    const data = cloneDeep(menuData);
    mapEach(data, level);
    return data
}
function mapEach(data, level) {
    data.forEach(item => {
        item.level = 'level' + level;
        if (item.children && item.children.length > 0) {
            mapEach(item.children, level + 1);
        }
    });
}
const menus = ref(mapLevel(menuData))
</script>
    
<style scoped>
.menu {
    width: 300px;
}
</style>